﻿using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SiSuoDemo01
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public async Task<int> Test()
        {
            Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} Test 被执行");
            await Task.Delay(2000);//这里还在ui线程 
            return 10;
        }

        /// <summary>
        /// 正常的代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private async void Button_Click(object sender, RoutedEventArgs e)
        //{
        //    Console.WriteLine($"Thread Id:{Environment.CurrentManagedThreadId}");
        //    var res = await Test().ConfigureAwait(false);
        //    txt.Text = res.ToString();
        //    Console.WriteLine($"Thread Id:{Environment.CurrentManagedThreadId}");
        //}



        /// <summary>
        /// 会造成死锁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            List<Task> taskLists = new List<Task>();
            for (int i = 0; i < 10; i++)
            {
                taskLists.Add(Test());
            }
            await Task.WhenAll(taskLists);

            Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} Thread Id:{Environment.CurrentManagedThreadId}");
            var res = Test().Result;//阻塞了ui线程   ui线程正在被阻塞   跟【await Task.Delay(2000);//这里还在ui线程 】矛盾了
            txt.Text = res.ToString();
            Console.WriteLine($"Thread Id:{Environment.CurrentManagedThreadId}");
        }
    }
}